use crate::models::attribute_groups::{CreateParams, Model};
use axum::debug_handler;
use loco_rs::prelude::*;

#[debug_handler]
async fn create(
    State(ctx): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let attribute_group = Model::create(&ctx.db, &params).await?;
    format::json(attribute_group)
}

#[debug_handler]
async fn find_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let attribute_group = Model::find_by_id(&ctx.db, &id).await?;
    format::json(attribute_group)
}

#[debug_handler]
async fn find_by_position(State(ctx): State<AppContext>, Path(position): Path<i32>) -> Result<Response> {
    let attribute_group = Model::find_by_position(&ctx.db, position).await?;
    format::json(attribute_group)
}

#[debug_handler]
async fn update_position(
    State(ctx): State<AppContext>,
    Path(id): Path<String>,
    Json(position): Json<i32>,
) -> Result<Response> {
    let attribute_group = Model::find_by_id(&ctx.db, &id).await?;
    let attribute_group = attribute_group
        .into_active_model()
        .update_position(&ctx.db, position)
        .await?;
    format::json(attribute_group)
}

#[debug_handler]
async fn delete_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let attribute_group = Model::find_by_id(&ctx.db, &id).await?;
    attribute_group.delete(&ctx.db).await?;
    format::json(())
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("attribute-groups")
        .add("/", post(create))
        .add("/:id", get(find_by_id))
        .add("/code/:code", get(find_by_position))
        .add("/:id/sort-order", put(update_position))
        .add("/:id", delete(delete_by_id))
}
